package com.inspur.edp.ai.flow.spi;

import com.inspur.edp.ai.flow.exception.FlowException;
import com.inspur.edp.common.type.enhanced.EnhancedServiceLoader;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.commons.utils.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lizhaorui
 * @date 2025/9/3
 * @description 节点执行器工厂类，根据节点类型获取节点执行器
 */

public class NodeExecutorFactory {

    private static Map<String, NodeExecutor> PROVIDER_MAP;

    public static NodeExecutor get(String kind) {
        if (StringUtils.isEmpty(kind)) {
            throw new FlowException("node executor type can not be empty.");
        }
        if (PROVIDER_MAP == null) {
            synchronized (NodeExecutorFactory.class) {
                if (PROVIDER_MAP == null) {
                    ConcurrentHashMap<String, NodeExecutor> temp = new ConcurrentHashMap<>();
                    List<Object> objectList = EnhancedServiceLoader.loadFile("META-INF/services/" + NodeExecutor.class.getName(), NodeExecutorFactory.class.getClassLoader());
                    for (Object obj : objectList) {
                        NodeExecutor nodeExecutor = (NodeExecutor) obj;
                        temp.put(nodeExecutor.getKind(), nodeExecutor);
                    }
                    PROVIDER_MAP = temp;
                }
            }
        }
        NodeExecutor executor = PROVIDER_MAP.get(kind);
        if (executor != null) {
            return executor;
        } else {
            throw new FlowException("not find node executor provider " + kind);
        }
    }

}